package com.xueba.manage.course.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xueba.framework.common.exception.ExceptionCast;
import com.xueba.framework.common.model.response.CommonCode;
import com.xueba.framework.common.model.response.QueryResponseResult;
import com.xueba.framework.common.model.response.QueryResult;
import com.xueba.framework.common.model.response.ResponseResult;
import com.xueba.framework.domain.course.CourseBase;
import com.xueba.framework.domain.course.ext.CourseInfo;
import com.xueba.framework.domain.course.request.CourseListRequest;
import com.xueba.manage.course.dao.CourseBaseRepository;
import com.xueba.manage.course.dao.CourseMapper;
import com.xueba.manage.course.service.CourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Kidy
 * @date 2020/7/31 11:50
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public QueryResponseResult<CourseInfo> findCourseList(int page, int size, CourseListRequest courseListRequest) {
        //保证数据的正确性
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 6;
        }
        if (null == courseListRequest.getSearch()) {
            courseListRequest.setSearch("");
        }
        courseListRequest.setSearch("%" + courseListRequest.getSearch() + "%");
        // 设置分页
        PageHelper.startPage(page - 1, size);
        // 从数据库查询数据
        Page<CourseInfo> courseBasePage = courseMapper.findCourseList(courseListRequest);
        // 设置查询结果
        QueryResult<CourseInfo> queryResult = new QueryResult<>();
        queryResult.setList(courseBasePage.getResult());
        queryResult.setTotal(courseBasePage.getTotal());
        // 返回响应结果(包含结果代码和查询结果)
        return new QueryResponseResult<>(CommonCode.SUCCESS, queryResult);
    }

    @Override
    public ResponseResult addCourseBase(CourseBase courseBase) {
        //校验数据是否合法
        //StringUtils.isNoneBlank() 返回true:所有的参数都不为空,null或空格
        if (null == courseBase ||
                StringUtils.isNoneBlank(courseBase.getTitle(),
                        courseBase.getGrade(),
                        courseBase.getMt(),
                        courseBase.getSt(),
                        courseBase.getDescription())) {
            //
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //新增的课程 设置为'未发布'状态
        courseBase.setStatus("未发布");
        courseBase.setId(null);
        //保存数据到数据库
        courseBaseRepository.save(courseBase);
        //返回响应的成功代码
        return ResponseResult.SUCCESS();
    }
}
